package cn.itcast.bos.action.base;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Actions;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

import cn.itcast.bos.domain.base.Standard;
import cn.itcast.bos.service.base.StandardService;

@ParentPackage("json-default")//因为分页查询需要返回json格式对象，所以需要继承json父包
@Namespace("/")
@Controller
@Scope("prototype")
@Actions
public class StandardAction extends ActionSupport implements ModelDriven<Standard>{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	//模型驱动接受表单中提交过来的standard对象
	private Standard standard = new Standard();
	
	@Override
	public Standard getModel() {
		return standard;
	}

	//注入Service
	@Autowired
	private StandardService standardService;
	
	//添加收派标准
	
	@Action(value="standard_save",
			results={@Result(name="success",type="redirect",
				location="./pages/base/standard.html")})
	public String standardSave(){
		//调用业务层完成添加收派标准操作
		standardService.save(standard);
		return SUCCESS;
	}
	
	//采用属性驱动接收数据表格的两个请求参数
	private int page;//当前页码
	private int rows;//每页需要先显示条数
	
	public void setPage(int page) {
		this.page = page;
	}

	public void setRows(int rows) {
		this.rows = rows;
	}

	//分页查询收派标准
	/**分页查询要做的不是页面的跳转，而是JSON数据的返回*/
	@Action(value="standard_pageQuery",results={@Result(name="success",type="json")})
	public String pageQueyr(){
		//构造分页查询对象
		Pageable pageable = new PageRequest(page-1, rows);//注意page是从0开始的
		
		//调用业务层完成查询操作
		//standardService.findALL(pageable)返回的是一个Page对象
		Page<Standard> pageData=standardService.pageQuery(pageable);
		
		//将返回结果转换为datagrid需要的形式
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("total", pageData.getTotalElements());
		map.put("rows", pageData.getContent());
		
		//将转换后的数据压入值栈转换为JSON返回给datagrid(需要用到struts2-json-plugin插件)
		ActionContext.getContext().getValueStack().push(map);
		return SUCCESS;
	}
	
	//查询所有收派标准
	@Action(value="standard_findAll",results={@Result(name="success",type="json")})
	public String findAllStandards(){
		
		//调用业务层完成查询所有收派标准
		List<Standard> list=standardService.findAll();
		
		//将查询结果转换为JSON返回给datagrid
		ActionContext.getContext().getValueStack().push(list);
		return SUCCESS;	
	}
}
